import datetime
import logging
import time

from sqlalchemy import func

from base.connection import mongodb_util, get_db_session
from conf import config
from conf.logging import LOGGING_DICT_CONFIG

logger = logging.getLogger("wechat")


class Statistics(object):
    def __init__(self):
        pass

    @staticmethod
    def _get_start_end_time(mark_date):
        """
        获取开始时间和结束时间
        :param mark_date: 标记时间，例如 20171101
        :return:
        """
        start_time = datetime.datetime.fromtimestamp(time.mktime(time.strptime(mark_date, "%Y%m%d")))
        end_time = start_time + datetime.timedelta(seconds=86399)
        return start_time, end_time

    def _stats_by_agency_uid(self, agency_uid, mark_date):
        class Benefit(object):
            pass

        class CashApply(object):
            pass

        session = get_db_session([
            {"db_table": "sdet_benefit", "model": Benefit},
            {"db_table": "slbt_cash_apply", "model": CashApply},
        ])
        # 计算出时间段
        start_time, end_time = self._get_start_end_time(mark_date)

        filter_params = dict(
            agency_uid=agency_uid,
            status=1,
            is_valid=1,
            is_finish=1
        )
        # 根据时间段来查询
        order_total_fee = session.query(func.sum(Benefit.order_fee)).filter_by(**filter_params).filter(
            Benefit.update_time >= start_time).filter(
            Benefit.update_time <= end_time).scalar()

        order_total_fee = float(order_total_fee) if order_total_fee else 0

        total_fee = session.query(func.sum(Benefit.fee)).filter_by(**filter_params).filter(
            Benefit.update_time >= start_time).filter(
            Benefit.update_time <= end_time).scalar()

        total_fee = float(total_fee) if total_fee else 0

        # 包括预收益的订单(订单号不重复)
        order_count = session.query(Benefit.order_id).filter_by(agency_uid=agency_uid, is_valid=1).filter(
            Benefit.update_time >= start_time).filter(
            Benefit.update_time <= end_time).filter(
            Benefit.status.in_([0, 1])).distinct().count()
        logger.info("计算结果：agency_uid=%s,mark_date=%s,order_total_fee=%s,total_fee=%s,order_count=%s", agency_uid,
                    mark_date, order_total_fee, total_fee, order_count)
        return order_total_fee, total_fee, order_count

    def calculate_daily(self, mark_date):
        # 检查是否已经计算过了
        db = mongodb_util.db
        record = db.ebc_benefit_daily.find_one({"mark_date": mark_date})
        if record:
            logger.info("已经计算过了：mark_date=%s" % mark_date)
            return

        class Agency(object):
            pass

        session = get_db_session([
            {"db_table": "ebt_agency", "model": Agency},
        ])
        # 取出所有的合伙人
        agencies = session.query(Agency).filter_by(ebf_factory_id=config.FACTORY_ID).all()
        for a in agencies:
            agency_uid = a.ebf_agency_uid
            order_total_fee, total_fee, order_count = self._stats_by_agency_uid(agency_uid, mark_date)
            doc = {"agency_uid": agency_uid,
                   "order_total_fee": order_total_fee,
                   "total_fee": total_fee,
                   "order_count": order_count,
                   "mark_date": mark_date,
                   "create_time": datetime.datetime.now()
                   }
            db.ebc_benefit_daily.insert(doc)

        logger.info("计算完成：mark_date=%s" % mark_date)


if __name__ == "__main__":
    import logging.config

    logging.config.dictConfig(LOGGING_DICT_CONFIG)
    Statistics().calculate_daily("20171103")
    pass
